<?php
/**
 * 广告图片
 * @author 江羿平<hugcolin@163.com>
 */

use Core\AdminController;
use Models\Ad;
class AdController extends AdminController {

	protected $types = array();

	public function __construct(){
		parent::__construct();
		$this->types = CONFIG('basic.ad');
	}

	/**
	 * 列表页
	 */
	public function index(){
		$ad = new Ad;
		$type = $this->input->get('type');
		if($type){
			$ad->where('type',$type);
		}
		$data['ads'] = $ad->order_by('sort','desc')->order_by('id','desc')->get();
		$data['types'] = $this->types;
		$data['type'] = $type;
		$this->load->view('admin/ad/index',$data);
	}
	

	/**
	 * 添加页面
	 */
	public function add(){
		$data['types'] = $this->types;
		$data['back_url'] = $this->input->server('HTTP_REFERER');
		$this->load->view('admin/ad/add',$data);
	}

	/**
	 * 编辑页面
	 */
	public function edit($id){
		$data['types'] = $this->types;
		$ad = new Ad;
		$data['ad'] = $ad->find(intval($id));
		$data['back_url'] = $this->input->server('HTTP_REFERER');
		$this->load->view('admin/ad/add',$data);
	}

	/**
	 * 删除
	 */
	public function delete(){
		$ad = new Ad;
		$ad->delete($this->input->post('id'));
		echo json_encode(array('code'=>0,'msg'=>'ok'));
	}


	/**
	 * 提交保存
	 */
	public function save(){
		
		$data['type'] = $this->input->post('type');
		$data['title'] = $this->input->post('title')?$this->input->post('title'):'#';
		$data['content'] = $this->input->post('content');
		$data['image'] = $this->input->post('image');
		$data['sort'] = intval($this->input->post('sort'))?intval($this->input->post('sort')):0;
		$data['url'] = $this->input->post('url')?$this->input->post('url'):'#';

		if(!$data['type'] || !$data['title'] || !$data['image']){
			echo json_encode(array('code'=>2,'msg'=>json_encode($data)));
			exit;
		}

		$ad = new Ad;
		if(intval($this->input->post('id'))){
			$ad->update(intval($this->input->post('id')),$data);
			echo json_encode(array('code'=>0,'msg'=>'ok'));
		}else{
			$data['create_time'] = time();
			$ad_id = $ad->add($data);
			if($ad_id){
				echo json_encode(array('code'=>0,'msg'=>'ok','ad_id'=>$ad['id']));	
			}else{
				echo json_encode(array('code'=>1));
			}
		}
	}

}
